const moment = require("moment");
const qr = require("qr-image");
import config from "../config";
// const fetch = require('node-fetch');
const axios = require("axios");
const Api = {
  path: config.webhooks,
};
// > installUrl: <font color=\"blue\">${version.installUrl}</font>
const markdown = (app, version, branch, t, type) => {
  const currentTime = moment(new Date()).format("YYYY-MM-DD hh:mm");

  const contentText = `分支：${branch}\n
    > 平台：<font color=\"comment\">${app.platform}</font>\n
    > 版本：<font color=\"comment\">${version.versionStr}</font>\n
    > AppName：<font color=\"comment\">${app.appName}</font>\n
    > 预览页：<font color=\"comment\">${config.baseUrl}/${app.shortUrl}</font>\n
    > 发布时间：<font color=\"comment\">${currentTime}</font>\n
    > ChangeLog: <font color=\"comment\">${version.changelog}</font>\n
    [点击扫码安装](${t})`;
  return type == "weixin" ? {
        msgtype: "markdown",
        markdown: {
          content: contentText,
        },
      }
    : {
        msgtype: "actionCard",
        actionCard: {
          title: `${app.appName}_${branch}构建通知`,
          text: `#### ${app.appName}${branch}构建成功 \n\n 分支：${branch}\n\n 平台：${app.platform} \n\n  版本：${version.versionStr} \n\nChangeLog：${version.changelog}\n\n 发布时间：${currentTime}`,
          btnOrientation: "0",
          btns: [
            {
              title: "预览页",
              actionURL: `http://${config.baseHost}/${app.shortUrl}`,
            },
          ],
        },
      };
};
const lan = async (app, version, branch, t) => {
  const promises = Api.path.map((item) => {
    const markdownJson = markdown(app, version, branch, t, item.type);
    return axios.request({
      url: `${item.host}${item.path}${item.access_token}`,
      data: markdownJson,
      method: "post",
      headers: {
        "Content-Type": "application/json",
      },
    });
  });
  for (const p of promises) {
    const data = await p;
    console.log(data);
  }
};
/**
 *
 * @param {*} app  下载地址
 * @param {*} version  分支
 * @param {*} branch  平台
 */
const wePush = (app, version, branch) => {
  const image = qr.imageSync(version.installUrl);
  const base64 = image.toString("base64");
  const t = `data:image/png;base64,${base64}`;
  lan(app, version, branch, t);
};

module.exports = { wePush };
